//
//  HJInputController.m
//  XWC
//
//  Created by Hello on 2022/10/24.
//

#import "HJInputController.h"
#import "HJInputBar.h"
#import "TUIDefine.h"
#import "NSString+emoji.h"
#import "HJCommonModel.h"
#import "HJGradientButton.h"
#import "HJEmojiView.h"
#import "HJIM.h"
#import "HJChatGroupModel.h"

@interface HJInputController ()<TJTextViewDelegate, HTMoreViewDelegate, HJEmojiViewDelegate>

@property (nonatomic, assign) CGRect keyboardFrame;
@property (nonatomic, assign) HJInputStatus status;
@property (nonatomic, strong) HJEmojiView *emojiView;


@end

@implementation HJInputController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupViews];
}

- (void)setupViews {
    self.view.backgroundColor = UIColor.whiteColor;
    _status = HJInput_Status_Input_None;
    
    _inputBar = [[HJInputBar alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, TTextView_Height)];
    _inputBar.delegate = self;
    [self.view addSubview:_inputBar];
    [self queryMoreViewData];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:CGRectGetMaxY(self.inputBar.frame) + Bottom_SafeHeight];
    }
    if (_status == HJInput_Status_Input_Keyboard) {
        _status = HJInput_Status_Input_None;
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    if(_status == HJInput_Status_Input_Face){
        [self hideFaceAnimation];
    } else if(_status == HJInput_Status_Input_More){
        [self hideMoreAnimation];
    } else{
        //[self hideFaceAnimation:NO];
        //[self hideMoreAnimation:NO];
    }
    _status = HJInput_Status_Input_Keyboard;
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:keyboardFrame.size.height + CGRectGetMaxY(self.inputBar.frame)];
    }
    self.keyboardFrame = keyboardFrame;
}

- (void)hideFaceAnimation {
    self.emojiView.hidden = NO;
    self.emojiView.alpha = 1.0;

    self.inputBar.faceButton.selected = NO;

    __weak typeof(self) ws = self;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        ws.emojiView.alpha = 0.0;
 
    } completion:^(BOOL finished) {
        ws.emojiView.hidden = YES;
        ws.emojiView.alpha = 1.0;
        [ws.emojiView removeFromSuperview];
    }];
}

- (void)showFaceAnimation {
    [self.view addSubview:self.emojiView];

    self.emojiView.hidden = NO;
    CGRect frame = self.emojiView.frame;
    frame.origin.y = Screen_Height;
    self.emojiView.frame = frame;

    self.inputBar.faceButton.selected = YES;
    
    __weak typeof(self) ws = self;
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        CGRect newFrame = ws.emojiView.frame;
        newFrame.origin.y = CGRectGetMaxY(ws.inputBar.frame); //ws.inputBar.frame.origin.y + ws.inputBar.frame.size.height;
        ws.emojiView.frame = newFrame;
 
    } completion:nil];
}

- (void)hideMoreAnimation {
    self.moreView.hidden = NO;
    self.moreView.alpha = 1.0;
    self.inputBar.moreButton.selected = NO;

    TJWeakify(self)
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        weakself.moreView.alpha = 0.0;
    } completion:^(BOOL finished) {
        weakself.moreView.hidden = YES;
        weakself.moreView.alpha = 1.0;
        [weakself.moreView removeFromSuperview];
    }];
}

- (void)showMoreAnimation {
    if (!self.moreView.datas) {
        [self queryMoreViewData];
    }
    
    [self.view addSubview:self.moreView];
 
    self.moreView.hidden = NO;
    CGRect frame = self.moreView.frame;
    frame.origin.y = Screen_Height;
    self.moreView.frame = frame;
    
    self.inputBar.moreButton.selected = YES;

    TJWeakify(self)
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        CGRect newFrame = weakself.moreView.frame;
        newFrame.origin.y = weakself.inputBar.frame.origin.y + weakself.inputBar.frame.size.height;
        weakself.moreView.frame = newFrame;
    } completion:nil];
}

- (void)inputBarDidTouchVoice:(HJInputBar *)textView {
    if(_status == HJInput_Status_Input_Talk){
        return;
    }
    [_inputBar.inputTextView resignFirstResponder];
    [self hideFaceAnimation];
    [self hideMoreAnimation];
    _status = HJInput_Status_Input_Talk;
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:CGRectGetMaxY(self.inputBar.frame) + Bottom_SafeHeight];
    }
}

- (void)inputBarDidTouchMore:(HJInputBar *)textView {
    if(_status == HJInput_Status_Input_More){
        [self reset];
        return;
    }
    
    if(_status == HJInput_Status_Input_Face){
        [self hideFaceAnimation];
    }
    [_inputBar.inputTextView resignFirstResponder];
    [self showMoreAnimation];
    _status = HJInput_Status_Input_More;
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:CGRectGetMaxY(_inputBar.frame) + self.moreView.frame.size.height + Bottom_SafeHeight];
    }
}
 
- (void)inputBarDidTouchFace:(HJInputBar *)textView {
 
    if(_status == HJInput_Status_Input_More){
        [self hideMoreAnimation];
    }
    
    if(_status == HJInput_Status_Input_Face){
        [self reset];
        return;
    }
    
    [_inputBar.inputTextView resignFirstResponder];
    _status = HJInput_Status_Input_Face;
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:CGRectGetMaxY(_inputBar.frame) + self.emojiView.frame.size.height];
    }
    [self showFaceAnimation];
}

 
- (void)inputBarDidTouchKeyboard:(HJInputBar *)textView {
    if(_status == HJInput_Status_Input_More){
        [self hideMoreAnimation];
    }
    if (_status == HJInput_Status_Input_Face) {
        [self hideFaceAnimation];
    }
    _status = HJInput_Status_Input_Keyboard;
    [_inputBar.inputTextView becomeFirstResponder];
}

- (void)inputBar:(HJInputBar *)textView didChangeInputHeight:(CGFloat)offset {
    if(_status == HJInput_Status_Input_Face){
        [self showFaceAnimation];
    }
    else if(_status == HJInput_Status_Input_More){
        [self showMoreAnimation];
    }
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:self.view.frame.size.height + offset];
    }
}

- (void)inputBar:(HJInputBar *)textView didSendText:(NSString *)text {
    NSString *content = [text getInternationalStringWithfaceContent];
    if(_delegate && [_delegate respondsToSelector:@selector(inputController:didSendTextMessage:)]){
        [_delegate inputController:self didSendTextMessage:content];
    }
}
 
- (void)inputBar:(HJInputBar *)textView didSendVoice:(NSString *)path {
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didSendVoiceMessage:)]){
        [_delegate inputController:self didSendVoiceMessage:path];
    }
}

- (void)inputBarDidTouchClose:(HJInputBar *)textView {
    [self reset];
}

- (void)inputBarDidInputAt:(HJInputBar *)textView {
    if (_delegate && [_delegate respondsToSelector:@selector(inputControllerDidInputAt:)]) {
        [_delegate inputControllerDidInputAt:self];
    }
}

- (void)inputBar:(HJInputBar *)textView didDeleteAt:(NSString *)atText {
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didDeleteAt:)]) {
        [_delegate inputController:self didDeleteAt:atText];
    }
}

- (void)inputBarDidDeleteBackward:(HJInputBar *)textView {
    if (textView.inputTextView.text.length == 0) {
    }
}


- (void)inputTextViewShouldBeginTyping:(UITextView *)textView {
    
    if (_delegate && [_delegate respondsToSelector:@selector(inputControllerBeginTyping:)]) {
        [_delegate inputControllerBeginTyping:self];
    }
}

- (void)inputTextViewShouldEndTyping:(UITextView *)textView {
    
    if (_delegate && [_delegate respondsToSelector:@selector(inputControllerEndTyping:)]) {
        [_delegate inputControllerEndTyping:self];
    }
    
}




- (void)reset {
    if(_status == HJInput_Status_Input_None){
        return;
    }
    else if(_status == HJInput_Status_Input_More){
        [self hideMoreAnimation];
    }
    else if(_status == HJInput_Status_Input_Face){
        [self hideFaceAnimation];
    }

    _status = HJInput_Status_Input_None;
    [_inputBar.inputTextView resignFirstResponder];
    if (_delegate && [_delegate respondsToSelector:@selector(inputController:didChangeHeight:)]){
        [_delegate inputController:self didChangeHeight:CGRectGetMaxY(self.inputBar.frame) + Bottom_SafeHeight];
    }
}

- (void)moreView:(HJMoreView *)moreView didSelectMoreCell:(HJInputMoreCell *)cell {
    if ([self.delegate respondsToSelector:@selector(inputController:didSelectMoreCell:)]) {
        [self.delegate inputController:self didSelectMoreCell:cell];
    }
}

- (void)emojiViewDidSend:(HJEmojiView *)emojiView {
    if (_inputBar.inputTextView.text.length != 0) {
        if(_delegate && [_delegate respondsToSelector:@selector(inputController:didSendTextMessage:)]){
            [_delegate inputController:self didSendTextMessage:_inputBar.inputTextView.text];
            _inputBar.inputTextView.text = @"";
        }
    }
}

- (void)emojiViewDidBackDelete:(HJEmojiView *)emojiView {
    [_inputBar backDelete];
}

- (void)emojiView:(HJEmojiView *)emojiView didSelectFaceCellWithEmoji:(NSString *)emoji {
    [_inputBar addEmoji:emoji];
}
 
 
#pragma mark - lazy load
- (HJEmojiView *)emojiView
{
    if(!_emojiView){
        _emojiView = [[HJEmojiView alloc] initWithFrame:CGRectMake(0, _inputBar.frame.origin.y + _inputBar.frame.size.height, self.view.frame.size.width, TFaceView_Height + Bottom_SafeHeight)];
        _emojiView.delegate = self;
    }
    return _emojiView;
}
 
- (HJMoreView *)moreView {
    if(!_moreView){
        _moreView = [[HJMoreView alloc] initWithFrame:CGRectMake(0, _inputBar.frame.origin.y + _inputBar.frame.size.height, self.emojiView.frame.size.width, 0)];
        _moreView.delegate = self;
    }
    return _moreView;
}

- (void)queryMoreViewData {
    
    NSMutableArray *moreMenus = [NSMutableArray array];
    if (!_groupId) {
        [moreMenus addObject:[HJInputMoreCellData photoData]];
        [moreMenus addObject:[HJInputMoreCellData pictureData]];
        if (!TJIM_isSelf(_sessionUserd)) {
            [moreMenus addObject:[HJInputMoreCellData transferData]];
        }
        self.moreView.datas = moreMenus;
        return;
    }
    
    dispatch_async_sql_queue(^{
        
        [HJIM.shareIM.groupManager queryGroupInfoByGroupId:self.groupId completion:^(HJChatGroupModel * _Nullable groupModel) {
            
            NSArray *abilities = groupModel.abilities;
            for (NSString *value in abilities) {
                if (value.intValue == 1) {
                    [moreMenus addObject:[HJInputMoreCellData pictureData]];
                } else if (value.intValue == 2) {
                    [moreMenus addObject:[HJInputMoreCellData photoData]];
                }
                
                dispatch_async_main_queue(^{
                    self.moreView.datas = moreMenus;
                });
            }
        }];
    });
}
 
- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];
   
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
   
}

- (void)viewDidAppear:(BOOL)animated {
   [super viewDidAppear:animated];
   for (UIGestureRecognizer *gesture in self.view.window.gestureRecognizers) {
       gesture.delaysTouchesBegan = NO;
   }
   self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan = NO;
}

- (void)viewDidDisappear:(BOOL)animated
{
   [super viewDidDisappear:animated];
   
   [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
